<template>
	<div class="form-panel animate-fade">
		<div class="form-logo">
			<i class="fa fa-user-plus"></i>
		</div>
		<h2 class="form-title">创建新账户</h2>

		<div class="form-group">
			<label class="form-label">用户名</label>
			<div class="input-wrapper">
				<i class="fa fa-user"></i>
				<input type="text" class="form-input" placeholder="请设置用户名" v-model="registerForm.username"
					@blur="validateUsername" />
				<div v-if="usernameError" class="error-message">
					{{ usernameError }}
				</div>
			</div>
		</div>

		<div class="form-group">
			<label class="form-label">手机号</label>
			<div class="input-wrapper">
				<i class="fa fa-phone"></i>
				<input type="tel" class="form-input" placeholder="请输入手机号" v-model="registerForm.phone"
					@blur="validatePhone" />
				<div v-if="phoneError" class="error-message">{{ phoneError }}</div>
			</div>
		</div>

		<div class="form-group code-group">
			<label class="form-label">验证码</label>
			<div class="input-wrapper">
				<i class="fa fa-key"></i>
				<div class="code-input-and-btn">
					<input type="text" class="form-input code-input" placeholder="请输入验证码"
						v-model="registerForm.verificationCode" />
					<button class="code-btn" :disabled="countdown > 0" @click="getVerificationCode">
						{{ countdown > 0 ? `${countdown}s后重新获取` : "获取验证码" }}
					</button>
				</div>
				<div v-if="codeError" class="error-message">{{ codeError }}</div>
			</div>

		</div>

		<div class="form-group">
			<label class="form-label">密码</label>
			<div class="input-wrapper">
				<i class="fa fa-lock"></i>
				<input :type="registerForm.showPassword ? 'text' : 'password'" class="form-input" placeholder="请设置密码"
					v-model="registerForm.password" @blur="validatePassword" />
				<button type="button" class="toggle-password"
					@click="registerForm.showPassword = !registerForm.showPassword">
					<i :class="registerForm.showPassword ? 'fa fa-eye' : 'fa fa-eye-slash'
						"></i>
				</button>
			</div>
			<div v-if="passwordError" class="error-message">
				{{ passwordError }}
			</div>
		</div>

		<div class="form-group terms-group">
			<label class="checkbox-label">
				<input type="checkbox" v-model="registerForm.agreeTerms" />
				我已阅读并同意<a href="#" class="terms-link">服务条款</a>和<a href="#" class="terms-link">隐私政策</a>
			</label>
		</div>

		<button class="submit-btn" @click="handleRegister" :class="{ disabled: !registerForm.agreeTerms }">
			注册
		</button>
	</div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { sendVerificationCode, register } from '@/api/internal-api/auth/auth-api'
import { alertInfo, alertSuccess } from '@/util/alert';
import { useAuthStore } from '@/stores/auth-store';

// const emit = defineEmits(['switch-tab']);

const registerForm = reactive({
	username: "",
	phone: "",
	verificationCode: "",
	password: "",
	showPassword: false,
	agreeTerms: false,
});

const countdown = ref(0);
let countdownTimer = null;

// 表单验证
const usernameError = ref("");
const phoneError = ref("");
const codeError = ref("");
const passwordError = ref("");

// 重置表单错误
const resetFormErrors = () => {
	usernameError.value = "";
	phoneError.value = "";
	codeError.value = "";
	passwordError.value = "";
};

// 用户名验证
const validateUsername = function () {
	if (!registerForm.username) {
		usernameError.value = "请输入用户名";
	} else if (registerForm.username.length < 3) {
		usernameError.value = "用户名长度至少为3个字符";
	} else {
		usernameError.value = "";
	}
	return !usernameError.value;
};

// 手机号验证
const validatePhone = () => {
	const phonePattern = /^1[3-9]\d{9}$/;
	if (!registerForm.phone) {
		phoneError.value = "请输入手机号";
	} else if (!phonePattern.test(registerForm.phone)) {
		phoneError.value = "请输入有效的手机号";
	} else {
		phoneError.value = "";
	}
	return !phoneError.value;
};

// 获取验证码
const getVerificationCode = async () => {
	if (!validatePhone()) return;

	if (! await sendVerificationCode(registerForm.phone)) return;

	// 设置倒计时
	countdown.value = 60;
	countdownTimer = setInterval(() => {
		countdown.value--;
		if (countdown.value <= 0) {
			clearInterval(countdownTimer);
		}
	}, 1000);
};

// 密码验证
const validatePassword = () => {
	if (!registerForm.password) {
		passwordError.value = "请输入密码";
	} else if (registerForm.password.length < 6) {
		passwordError.value = "密码长度至少为6个字符";
	} else {
		passwordError.value = "";
	}
	return !passwordError.value;
};

// 注册处理
const handleRegister = async () => {
	// 完整验证
	const isUsernameValid = validateUsername();
	const isPhoneValid = validatePhone();
	const isPasswordValid = validatePassword();

	if (!isUsernameValid || !isPhoneValid || !isPasswordValid) {
		return;
	}

	if (!registerForm.verificationCode) {
		codeError.value = "请输入验证码";
		return;
	}

	if (!registerForm.agreeTerms) {
		alertInfo("请同意服务条款和隐私政策");
		return;
	}

	if (! await register(registerForm)) return

	alertSuccess("注册成功！")
	useAuthStore().autoLogin(registerForm.username, registerForm.password)
	//   emit('after-register', registerForm.username, registerForm.password)

};

// 清理倒计时
onBeforeUnmount(() => {
	if (countdownTimer) {
		clearInterval(countdownTimer);
	}
});
</script>

<style lang="scss" scoped>
@use '../style/form-style.scss';

/* 验证码区域 */
.code-group {
	margin-bottom: 28px;
}

.code-input-and-btn {
	display: flex;
	justify-content: space-between;
	padding: 1px 22px 1px 0;
}

.code-btn {
	height: 48px;
	padding: 0 16px;
	background-color: var(--light-bg);
	color: var(--primary-color);
	border: 1px solid var(--border-color);
	border-radius: 8px;
	font-size: 14px;
	font-weight: 500;
	cursor: pointer;
	transition: all 0.2s ease;
	white-space: nowrap;
}

.code-btn:hover:not(:disabled) {
	background-color: #f3f4f6;
}

.code-btn:disabled {
	background-color: #f9fafb;
	color: #9ca3af;
	cursor: not-allowed;
}

.error-message {
	position: absolute;
	color: red;
	font-size: 14px;
}
</style>